import base64
import pickle

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from carts.serializers import CartSerializer, CartSKUSerializer, CartDeleteSerializer, CartSelectAllSerializer
from goods.models import SKU


class CartView(APIView):
    """操作购物车：增删改查"""

    def perform_authentication(self, request):
        """
        禁用验证/延后验证
        重写父类的用户验证方法，不在进入视图前就检查JWT
        """
        pass

    def post(self, request):
        """
        添加购物车
        """
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 创建响应对象
        response = Response(serializer.data, status=status.HTTP_201_CREATED)

        # 尝试对请求的用户进行验证
        try:
            user = request.user
            # 如果代码能继续向下走说明是登录用户存储购物车数据到redis
            # 用户已登录，在redis中保存
            # 创建redis连接对象
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 记录购物车商品数量
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            # 记录购物车的勾选项
            # 勾选
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            pl.execute()

        except:
            # 验证失败，用户未登录存储购物车数据到cookie
            # 用户未登录，在cookie中保存
            # {
            #     1001: { "count": 10, "selected": true},
            #     ...
            # }
            # 使用pickle序列化购物车数据，pickle操作的是bytes类型

            cart = request.COOKIES.get('carts')
            # 判断是否有购物车数据
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

            sku = cart.get(sku_id)
            if sku:
                count += int(sku.get('count'))

            cart[sku_id] = {
                'count': count,
                'selected': selected
            }

            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            # 设置购物车的cookie
            # 需要设置有效期，否则是临时cookie
            response.set_cookie('carts', cookie_cart, max_age=365 * 24 * 60 * 60)
        return response

    def get(self, request):
        """查询购物车"""
        try:
            user = request.user
            # 若获取到user则说明已经登录用户(操作redis数据库)
        except:
            # 若没有获取到user则说明是未登录用户(获取cookie数据库)
            user = None
        else:

            # 若获取到user则说明已经登录用户(操作redis数据库)
            # 创建redis连接对象
            redis_conn = get_redis_connection('cart')
            # 获取hash数据 {sku_id16: 1, sku_id2: 2}
            cart_redis_dict = redis_conn.hgetall('cart_%d' % user.id)
            # 获取set数据
            selected_ids = redis_conn.smembers('selected_%d' % user.id)
            # 把redis的购物车数据转换成和cookie购物车数据格式一样

            # 定义一个用来转换数据格式的大字典
            cart_dict = {}

            for sku_id_bytes in cart_redis_dict:
                cart_dict[int(sku_id_bytes)] = {
                        'count': int(cart_redis_dict[sku_id_bytes]),
                        'selected': sku_id_bytes in selected_ids
                    }
        if not user:

            # 若没有获取到user则说明是未登录用户(获取cookie数据库)
            cart_str = request.COOKIES.get('carts')
            # 判断是否有cookie购物车数据

            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 获取购物车中所有商品的sku模型
        skus = SKU.objects.filter(id__in=cart_dict.keys())

        # 遍历skus查询集,给里面的每个sku模型追加两个属性

        for sku in skus:
            sku.count = cart_dict[sku.id]['count']
            sku.selected = cart_dict[sku.id]['selected']

        # 创建序列化器进行序列化操作
        serializer = CartSKUSerializer(skus, many=True)

        return Response(serializer.data)

    def put(self, request):
        """修改购物⻋"""
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 响应
        response = Response(serializer.data)

        # 尝试对请求的用户进行验证
        try:
            user = request.user
        except:
            # 验证失败，用户未登录
            user = None

        else:
            # 用户已登录，在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 创建redis连接对象 hash 字典: {sku_id_16: 2, sku_id_2: 1}
            # 勾选状态 set集合中 {sku_id_16, sku_id_2}
            # 修改指定sku_id的购买数据 把hash字典中指定sku_id的value覆盖掉
            pl.hset('cart_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                pl.srem('cart_selected_%s' % user.id, sku_id)
            pl.execute()


        if not user:
            # 用户未登录，在cookie中保存
            # 使用pickle序列化购物车数据，pickle操作的是bytes类型
            cart = request.COOKIES.get('carts')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}
            # 直接覆盖商品的数据及勾选状态
            cart[sku_id] = {
                'count': count,
                'selected': selected
            }
            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()


            # 设置购物车的cookie
            # 需要设置有效期，否则是临时cookie
            response.set_cookie('carts', cookie_cart, max_age=365 * 24 * 60 * 60)
        return response

    def delete(self, request):
        """删除购物⻋"""

        serializer = CartDeleteSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data['sku_id']

        response = Response(status=status.HTTP_204_NO_CONTENT)

        try:
            user = request.user
        except:
            # 验证失败，用户未登录
            user = None

        else:
            # 已登录用户操作redis购物车数据
            # 创建redis连接对象
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 把本次要删除的sku_id从hash字典中移除
            pl.hdel('cart_%d' % user.id, sku_id)
            # 把本次要删除的sku_id从set集合中移除
            pl.srem('selected_%d' % user.id, sku_id)
            pl.execute()

        if not user:
            # 未登录用户操作cookie购物车数据
            # 获取cookie数据
            cart = request.COOKIES.get('carts')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
                if sku_id in cart:
                    del cart[sku_id]
                if len(cart.keys()):  # if成立给cookie字典中还有商品
                    cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                    # 设置购物车的cookie
                    # 需要设置有效期，否则是临时cookie

                    response.set_cookie('carts', cookie_cart, max_age=365 * 24 * 60 * 60)
                else:
                    # 如果cookie购物车数据已经全部删除,就把cookie移除
                    response.delete_cookie('carts')
        return response


class CartSelectAllView(APIView):
    """
    购物车全选
    """

    def perform_authentication(self, request):
        """
        重写父类的用户验证方法，不在进入视图前就检查JWT
        """
        pass

    def put(self, request):

        # 创建序列器进行反序列化
        serializer = CartSelectAllSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        selected = serializer.validated_data.get('selected')

        response = Response(serializer.data)

        try:
            user = request.user
        except:
            user = None
        else:
            # 已登录用户操作redis
            # 创建redis连接对象
            redis_conn = get_redis_connection('cart')
            # 获取redis中的hash字典
            cart_redis_dict = redis_conn.hgetall('cart_%d' % user.id)
            # 判断是全选还是取消全选
            if selected:
                # 如果是全选把所有sku_id添加到set集合中
                redis_conn.sadd('selected_%d' % user.id, *cart_redis_dict.keys())
            else:
                # 如果取消全选把所有sku_id从set集合中移除
                redis_conn.srem('selected_%d' % user.id, *cart_redis_dict.keys())

        if not user:
            # 未登录用户操作cookie
            # 获取cookie数据
            cart_str = request.COOKIES.get('carts')
            # 把cart_str 转换成cart_dict
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
                # for sku_id, sku_id_dict in cart_dict.items():
                # 遍历cookie字典
                for sku_id in cart_dict:
                    # 取出每个sku_id对应的小字典
                    sku_id_dict = cart_dict[sku_id]
                    # 是全选把selected全部改为True否则改为False
                    sku_id_dict['selected'] = selected

                # 把cart_dict 转换成 cart_str
                cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
                # 设置cookie
                response.set_cookie('carts', cart_str)

        return response